define(function(require){
	var main = require('/static/main.js');
    require('/static/ajaxfileupload.js');
	require('/static/vue.js');
	var m = new main();
	var bbargin = {
        vueData:'',
		_init:function(){
		    this.ajaxUpload('MainSrc');
		    this.ajaxUpload('wxMainSrc');
            this.ajaxUpload('CoverSrc');

            if($_GET['id']){
                m.loadmenu('.cate-drainage',2);
                $('.q-tit-change').html('<a href="/drainage/newregister">新人礼包活动管理</a> > 编辑');
                $('.SaveBtn').html('完成');
                this.getdetial();
            }else{
                m.loadmenu('.cate-drainage',0);
            }

			this.bindValue();
			this.bindEvent();
		},
		bindValue:function(){
			this.vueData = new Vue({
			  el: '#changeEvent',
			  data: {
			    ActName: '',
			    RedPacketPrice: '',
			  },
			  watch: {
			    ActName: function(newValue,oldeValue) {
			     	$(".head_tit_center").html(newValue)
			    },
			    RedPacketPrice: function(newValue,oldeValue){
			     	$(".packetindex_totm i").html(newValue)
			    },
			  }
			})
		},
        getdetial:function(){
            var _this = this;
            $.ajax({
                type: "POST",
                url:'/drainage/newregister-detial',
                data:{GiftPackId:$_GET['id']},
                dataType: "json",
                success: function (ret) {
                    if(ret.IsBizSuccess){
                        var v = ret.Model
                        _this.vueData.ActName = v.ActName
                        _this.vueData.RedPacketPrice = v.RedPacketPrice

                        $('.ActName').val(v.ActName);
                        $(".head_tit_center").html(v.ActName)
                        $('.RedPacketPrice').val(v.RedPacketPrice);
                        $(".packetindex_totm i").html(v.RedPacketPrice)
                        $('#CoverSrc').attr('data-src',v.CoverSrc)
                        $('.Comment').val(v.Comment)

                        // $('.bargain_banner img').attr('data-src')
                        $('.bargain_banner img').attr({'src':v.TitleSrc,'data-src':v.TitleSrc})
                        $('#StartDate').val(m.formatTimeAll2(v.StartTime))
                        $('#EndDate').val(m.formatTimeAll2(v.EndTime))
                        _this.countTime(m.formatTimeAll2(v.EndTime),m.formatTimeAll2(v.StartTime));
                        if(v.IsOpen){
                            $(".isopen").click();
                        }
                        $('.Hotline').val(v.Hotline)
                        $('.ActCnt').val(v.ActCnt)
                        $('.RedPacketCnt').val(v.RedPacketCnt)

                        document.getElementById('PlayingDescribe').innerHTML = v.PlayingDescribe
                        $('.PlayingDescribe').html(v.PlayingDescribe);


                        $('.ShareTitle').val(v.ShareTitle)
                        $('.ShareContent').val(v.ShareContent)
                        $('#wxMainSrc').attr('data-src',v.ShareSrc)

                    }else{
                        layer.msg(ret.ErrMsg);
                        return false;
                    }
                }
            });
        },
		bindEvent:function(){
			var _this = this;
			var start = '';
			//初始化日期控件
             $('#StartDate').datetimepicker({
               format:'yyyy-mm-dd hh:ii',
               language:'zh-CN',
               autoclose: true,
               'startDate':new Date()
            }).on("changeDate",function(ev){
               start = $("#StartDate").val();
               $('#EndDate').datetimepicker('setStartDate',start)
               _this.countTime(start)

            });
            $('#EndDate').datetimepicker({
               format:'yyyy-mm-dd hh:ii',
               language:'zh-CN',
               autoclose: true,
               'startDate':new Date()
            }).on("changeDate",function(ev){
               var endtime = $("#EndDate").val();
               $('#StartDate').datetimepicker('setEndDate',endtime)
               _this.countTime(endtime,start)
            });

			// 创建活动
			$('.SaveBtn').click(function(){
                var $this = $(this);
				var data = {
					// 活动信息
					ActName:$('.ActName').val(),
					TitleSrc:$('.bargain_banner img').attr('data-src'),
					StartTime:$('#StartDate').val(),
					EndTime:$('#EndDate').val(),
					IsOpen:$('.isuseable').is(":checked"), 
                    CoverSrc: $('#CoverSrc').attr('data-src'),
                    Comment:$('.Comment').val(),
					
					// 配置信息
                    Hotline:$('.Hotline').val(),
					RedPacketPrice:$('.RedPacketPrice').val(),
                    ActCnt:$('.ActCnt').val(),
                    RedPacketCnt:$('.RedPacketCnt').val(),
                    PlayingDescribe:document.getElementById('PlayingDescribe').innerHTML,

                    // 微信分享
                    ShareTitle:$('.ShareTitle').val(),
                    ShareContent:$('.ShareContent').val(),
                    ShareSrc:$('#wxMainSrc').attr('data-src'),

				}

                // console.log(data);
                // return false
				var alltrue = true;
            	var truearrya = [];
                data.TitleSrc = data.TitleSrc == undefined ? '' : data.TitleSrc
                data.ShareSrc = data.ShareSrc == undefined ? '' : data.ShareSrc
                data.CoverSrc = data.CoverSrc == undefined ? '' : data.CoverSrc

               
           		truearrya.push( bbargin.errorMessage(data.ActName,'actname','请填写活动名称'));
           		truearrya.push( bbargin.errorMessage(data.TitleSrc,'titlesrc','请上传活动主图'));
                truearrya.push( bbargin.errorMessage(data.CoverSrc,'coversrc','请上传活动封面图'));
                truearrya.push( bbargin.errorMessage(data.Comment,'comment','请填写活动描述'));
           		truearrya.push( bbargin.errorMessage(data.StartTime,'startdate','请选择活动开始时间'));
           		truearrya.push( bbargin.errorMessage(data.EndTime,'enddate','请选择活动结束时间'));
                truearrya.push( bbargin.errorMessage(data.Hotline,'hotline','请填写活动咨询电话'));
                truearrya.push( bbargin.errorMessage(data.RedPacketPrice,'redpacketprice','目标价格不能为空'));
                truearrya.push( bbargin.errorMessage(data.ActCnt,'actcnt','名额数不能为空'));
                truearrya.push( bbargin.errorMessage(data.RedPacketCnt,'redpacketcnt','目标价格不能为空'));
                truearrya.push( bbargin.errorMessage(data.PlayingDescribe,'playingdescribe','请填写玩法介绍'));

           		truearrya.push( bbargin.errorMessage(data.ShareTitle,'sharetitle','请填写微信分享标题'));
           		truearrya.push( bbargin.errorMessage(data.ShareContent,'sharecontent','请填写微信分享内容'));
           		truearrya.push( bbargin.errorMessage(data.ShareSrc,'sharesrc','请上传微信分享图片'));


           		$.each(truearrya,function(k,v){
	                if(v == false){
	                    alltrue = false;
	                    return false;
	                }
	            });
                if($_GET['id']){
                    data.GiftPackId = $_GET['id']
                }
                // console.log(data);
                // return false
                data.TitleSrc = _this.GetUrlRelativePath(data.TitleSrc);
                data.ShareSrc = _this.GetUrlRelativePath(data.ShareSrc);
                data.CoverSrc = _this.GetUrlRelativePath(data.CoverSrc);
                
                
	            if(alltrue){
                    var isclick = parseInt($this.attr('isclick'));
	            	if(isclick == 1){
		                $.ajax({
		                    type: "POST",
		                    url: "/drainage/createnewregester",
		                    data :data,
		                    dataType: "json",
		                    success: function (ret){
		                        if(ret.IsBizSuccess){
                                    if($_GET['id']){
                                        layer.msg("编辑成功");
                                    }else{
                                        layer.msg("创建成功");
                                    }
                                    $this.attr('isclick',0);
                                    setTimeout(function(){
                                        window.location.href="/drainage/newregister"
                                    },1000)
		                            return false;
		                        }else{
		                            layer.msg(ret.msg);
		                        }
		                    }
		                });
	            	}

	            }




			})
		},
		 //错误处理
        errorMessage:function(str,classname,errmsg){
            if(str.length < 1){
                var html = $(".pass-msg."+classname).html();
                if(html.length < 1){
                    $(".pass-msg."+classname).html(errmsg);
                }
               return false;
            }else{
                $(".pass-msg."+classname).html("");
                return true
            }
        },
		//倒计时
        countTime:function(endTime,startTime){
        	var _this = this;
            //倒计时
            var timesTramp =  Date.parse(endTime)/1000
        	var timestmp = startTime ? Date.parse(startTime)/1000 : Date.parse(new Date())/1000
            var ts =  (timesTramp - timestmp);//计算剩余的毫秒数
            var day = 0, hour = 0, minute = 0, second = 0; //时间默认值   
            day = parseInt(ts / (60 * 60 * 24));
            hour = parseInt(ts / (60 * 60)) - (day * 24);
            minute = parseInt(ts / 60) - (day * 24 * 60) - (hour * 60);
            second = parseInt(ts) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
            if (hour <= 9) hour = '0' + hour;
            if (minute <= 9) minute = '0' + minute;
            if (second <= 9) second = '0' + second;
            if(ts < 0){
                return false;
            }
            var str = '';
            str += '<span><i>'+day+'</i>天</span>\
                    <span><i>'+hour+'</i>时</span>\
                    <span><i>'+minute+'</i>分</span>\
                    <span><i>'+second+'</i>秒</span>';
            $(".count-time").html(str);
        },
		//上传图片
        ajaxUpload:function(obj){
            $(document).on("change",'#'+obj,function(e){
            	ajaxFileUpload();
            })
            function ajaxFileUpload(){
                $.ajaxFileUpload({
                    url:m.baseUrl+"/customer/edit-head",
                    secureuri: false,
                    fileElementId: obj,
                    dataType: 'json',
                    success: function (ret) {
                        if(ret.IsBizSuccess){
                        	if(obj == 'MainSrc'){
                                $('.bargain_banner img').attr('src',ret.Photo);
                        		$('.bargain_banner img').attr('data-src',ret.FileName);
                        	}else if(obj == 'wxMainSrc'){
                                $('#wxMainSrc').attr('data-src',ret.FileName);
                            }else if(obj == 'CoverSrc'){
                                $('#CoverSrc').attr('data-src',ret.FileName);
                            }
                        	$('#'+obj).siblings('.input-group').find('input').attr('placeholder',ret.FileName);
                        }else{
                            layer.msg(ret.ErrMsg);
                            return false;
                        }
                    }
                })
                return false;
            }
        },
         //去除域名获取相对路径
        GetUrlRelativePath:function(url){
            var arrUrl = url.split("//");
            var length = arrUrl.length;
            if(length > 1){
                var start = arrUrl[length-1].indexOf("/");
                var relUrl = arrUrl[length-1].substring(start);//stop省略，截取从start开始到结尾的所有字符
                if(relUrl.indexOf("?") != -1){
                    relUrl = relUrl.split("?")[0];
                }
                if (relUrl.substr(0,1)=='/') {
                    relUrl = relUrl.substr(1);
                }
                return relUrl;
            }else{
                return url;
            }
        }


	}
	
	// var ret = new Cont();
	bbargin._init();
	

	
})